<template>
  <div class="featured-template-management">
    <div class="page-header">
      <h1>精选模板管理</h1>
      <p>管理精选模板的标记、评判标准和自动化规则</p>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.totalFeatured }}</div>
              <div class="stat-label">总精选模板</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.adminFeatured }}</div>
              <div class="stat-label">管理员精选</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.userFeatured }}</div>
              <div class="stat-label">用户精选</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ stats.avgRating.toFixed(1) }}</div>
              <div class="stat-label">平均评分</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button type="primary" @click="triggerAutoMark" :loading="autoMarkLoading">
        <el-icon><Refresh /></el-icon>
        执行自动标记
      </el-button>
      <el-button @click="showCriteriaDialog = true">
        <el-icon><Setting /></el-icon>
        评判标准设置
      </el-button>
      <el-button @click="loadFeaturedTemplates">
        <el-icon><Refresh /></el-icon>
        刷新列表
      </el-button>
    </div>

    <!-- 精选模板列表 -->
    <div class="templates-section">
      <el-table 
        :data="featuredTemplates" 
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="name" label="模板名称" min-width="200">
          <template #default="{ row }">
            <div class="template-name">
              <strong>{{ row.name }}</strong>
              <el-tag v-if="row.createdBy === 'admin'" type="warning" size="small">管理员</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)" size="small">
              {{ getCategoryName(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="downloadCount" label="下载次数" width="100" sortable />
        
        <el-table-column prop="rating" label="评分" width="120">
          <template #default="{ row }">
            <div class="rating-display">
              <el-rate 
                :model-value="row.rating || 0" 
                disabled 
                size="small"
                show-score
                text-color="#ff9900" />
              <span class="rating-count">({{ row.ratingCount || 0 }})</span>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdBy" label="创建者" width="120" />
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              type="danger" 
              size="small" 
              @click="unmarkTemplate(row)"
              :loading="row.unmarking">
              取消精选
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评判标准设置对话框 -->
    <el-dialog 
      v-model="showCriteriaDialog" 
      title="精选模板评判标准" 
      width="500px">
      
      <el-form :model="criteria" label-width="120px">
        <el-form-item label="最小下载次数">
          <el-input-number 
            v-model="criteria.minDownloadCount" 
            :min="0" 
            :max="1000" />
        </el-form-item>
        
        <el-form-item label="最小评分">
          <el-input-number 
            v-model="criteria.minRating" 
            :min="0" 
            :max="5" 
            :step="0.1" 
            :precision="1" />
        </el-form-item>
        
        <el-form-item label="最小评分数量">
          <el-input-number 
            v-model="criteria.minRatingCount" 
            :min="0" 
            :max="100" />
        </el-form-item>
        
        <el-form-item label="最小使用次数">
          <el-input-number 
            v-model="criteria.minUseCount" 
            :min="0" 
            :max="1000" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCriteriaDialog = false">取消</el-button>
        <el-button type="primary" @click="updateCriteria" :loading="criteriaLoading">
          保存设置
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Setting } from '@element-plus/icons-vue'
import { TEMPLATE_CATEGORIES, getCategoryName, getCategoryType } from '@/constants/templateCategories'

// 响应式数据
const loading = ref(false)
const autoMarkLoading = ref(false)
const criteriaLoading = ref(false)
const showCriteriaDialog = ref(false)

const featuredTemplates = ref([])
const selectedTemplates = ref([])
const stats = ref({
  totalFeatured: 0,
  adminFeatured: 0,
  userFeatured: 0,
  avgDownloads: 0,
  avgRating: 0
})

const criteria = ref({
  minDownloadCount: 10,
  minRating: 4.0,
  minRatingCount: 5,
  minUseCount: 0
})

// 加载精选模板列表
const loadFeaturedTemplates = async () => {
  loading.value = true
  try {
    const response = await fetch('/api/featured-templates', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.code === 200) {
      featuredTemplates.value = result.data || []
    } else {
      throw new Error(result.message || '加载失败')
    }
  } catch (error) {
    ElMessage.error('加载精选模板列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStats = async () => {
  try {
    const response = await fetch('/api/featured-templates/stats', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.code === 200) {
      stats.value = result.data
    }
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 触发自动标记
const triggerAutoMark = async () => {
  autoMarkLoading.value = true
  try {
    const response = await fetch('/api/featured-templates/auto-mark', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      }
    })
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('自动标记任务已执行')
      await loadFeaturedTemplates()
      await loadStats()
    } else {
      throw new Error(result.message || '执行失败')
    }
  } catch (error) {
    ElMessage.error('执行自动标记失败: ' + error.message)
  } finally {
    autoMarkLoading.value = false
  }
}

// 取消精选标记
const unmarkTemplate = async (template) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消模板"${template.name}"的精选标记吗？`,
      '确认操作',
      { type: 'warning' }
    )
    
    template.unmarking = true
    
    const response = await fetch(`/api/featured-templates/${template.id}/unmark`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ reason: '管理员手动取消' })
    })
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('精选标记已取消')
      await loadFeaturedTemplates()
      await loadStats()
    } else {
      throw new Error(result.message || '操作失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消精选标记失败: ' + error.message)
    }
  } finally {
    template.unmarking = false
  }
}

// 更新评判标准
const updateCriteria = async () => {
  criteriaLoading.value = true
  try {
    const response = await fetch('/api/featured-templates/criteria', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(criteria.value)
    })
    
    const result = await response.json()
    if (result.code === 200) {
      ElMessage.success('评判标准已更新')
      showCriteriaDialog.value = false
    } else {
      throw new Error(result.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新评判标准失败: ' + error.message)
  } finally {
    criteriaLoading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedTemplates.value = selection
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadFeaturedTemplates()
  loadStats()
})
</script>

<style scoped>
.featured-template-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #606266;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}

.action-section {
  margin-bottom: 20px;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.rating-display {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating-count {
  font-size: 12px;
  color: #909399;
}
</style>
